<template>
  <div class="env-select">
    <el-select
      v-model="value"
      @change="handleEnvChange"
    >
      <el-option v-for="item in envList" :key="item.id" :label="item.name" :value="item.value" />
    </el-select>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getServerList, getAllServerList } from '@/api/deploy/dpServerConfig'
import { getAll as getAllResources } from '@/api/deploy/dpResourceStandards'
import { queryAll as queryAllUser } from '@/api/system/user'
import { getK8sList } from '@/api/deploy/dpK8sInstance'
import _ from 'lodash'
import crudNotifyAnnounceUser from '@/api/message/notifyAnnounceUser'

export default {
  name: 'Env',
  components: {},
  data() {
    return {
      value: '',

      // 已经弹窗过的消息
      hasNotifyMessageList: [],
      setIntRequest: null
    }
  },
  computed: {
    ...mapGetters([
      'envList',
      'env'
    ])
  },
  mounted() {
    this.getProjectList()
    this.getAllResources()
    this.getAllUser()
    this.getK8sInstanceList()
    this.value = this.env

    this.$nextTick(() => {
      this.startTimer()
    })
  },
  beforeDestroy() {
    this.stopIntRequest()
  },
  methods: {
    getAllUnreadMessage() {
      crudNotifyAnnounceUser.getAll({
        state: false
      }).then(messageList => {
        // 去重后通知
        const checkedIdList = this.hasNotifyMessageList.map(item => item.id)
        const newMessageList = messageList.filter(item => checkedIdList.indexOf(item.id) === -1) || []
        if (newMessageList.length > 0) {
          // 触发审核数据拉取
          this.$bus.$emit('global-approval-change')
          this.notify(newMessageList)
        }
      })
    },
    notify(messageList) {
      const len = messageList.length
      for (let i = 0; i < len; i++) {
        const message = messageList[i]

        setTimeout(() => {
          this.notifyMessage(message)
        }, 500)
      }
    },
    notifyMessage(message) {
      const _this = this
      const notifyAnnounce = message.notifyAnnounce
      this.$notify({
        title: notifyAnnounce.title,
        message: notifyAnnounce.message,
        type: notifyAnnounce.type,
        duration: notifyAnnounce.duration,
        onClose: function() {
          _this.handleMessageClose(message)
        },
        onClick: function() {
          this.close()
          if (notifyAnnounce.router) {
            _this.$router.push(notifyAnnounce.router)
          }
        }
      })
      this.hasNotifyMessageList.push(message)
    },
    handleMessageClose(message) {
      message.state = true
      crudNotifyAnnounceUser.edit(message).then(res => {
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    stopIntRequest() {
      this.setIntRequest && clearInterval(this.setIntRequest)
      this.setIntRequest = null // 内存回收
    },
    startTimer() {
      const _this = this
      this.setIntRequest = setInterval(() => {
        _this.getAllUnreadMessage()
      }, 10000)
    },
    handleEnvChange(value) {
      this.$store.dispatch('deploy/setEnv', value)
      this.$bus.$emit('global-env-change', value)

      // 刷新重载
      this.$router.push(`/`)
      this.$router.go(0)
    },
    getProjectList() {
      // 查询用户拥有的服务
      getServerList().then(data => {
        this.$store.dispatch('deploy/setProjectList', data)
      })

      // 查询全部服务
      getAllServerList({}).then(projectList => {
        const pMap = {}
        projectList.forEach(project => {
          pMap[project.projectId] = project.name
        })
        this.$store.dispatch('deploy/setProjectMap', pMap)
      })
    },
    getAllResources() {
      getAllResources().then(data => {
        this.$store.dispatch('deploy/setResourceList', data)
      })
    },
    getAllUser() {
      queryAllUser().then(data => {
        this.$store.dispatch('deploy/setUserList', data)
      })
    },
    getK8sInstanceList() {
      getK8sList(this.env).then(data => {
        const k8sList = []
        const len = data.length
        for (let index = 0; index < len; index++) {
          const instance = data[index]
          const tagsStr = instance.namespaceList
          if (tagsStr) {
            const tags = tagsStr.split(',')

            const namespaceLen = tags.length
            for (let ni = 0; ni < namespaceLen; ni++) {
              const namespace = tags[ni]
              const cloneInstance = _.clone(instance)
              cloneInstance['namespace'] = namespace
              cloneInstance['totalName'] = `${instance.name}[${namespace}]`
              k8sList.push(cloneInstance)
            }
          }
        }
        this.$store.dispatch('deploy/setK8sInstanceList', k8sList)
        this.$bus.$emit('global-env-change', this.value)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

  .env-select {
    width: 120px;
    padding: 0 0px;
    height: 100%;
    display: inline-block;
    margin-right: 5px;
    .s-select {
      margin-right: 5px;
    }
  }
</style>
